package net.elive.peer.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import net.elive.tools.Contants;
import net.elive.utils.LogUtils;

import org.apache.commons.logging.Log;

/**
 * 网络工具类型
 * @author jincool.cao@gmail.com
 *
 */
public class NetUtils {
	public static Log log = LogUtils.getLog(NetUtils.class);
	/**
	 * 设置中心服务器网络地址
	 */
	public static void setCIP(){
		while(true){
			try {
				Contants.C_IP = InetAddress.getByName(Contants.C_IP_STR);
				log.info(">>>>>>>>设置中心服务器网络地址:"+Contants.C_IP);
				break;
			} catch (UnknownHostException e) {
				log.info(">>>>>>>>设置中心服务器网络地址"+Contants.C_IP+"不存在:");
				e.printStackTrace();
				try {
					Thread.sleep(10*1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	/**
	 * 获取本机局域网IP
	 */
	public static void setLanIp(){
		while(true){
			try {
				Socket s = new Socket(Contants.C_IP,Contants.CHECK_LANIP_SERVERPORT_FIRST);
				Contants.LAN_IP =s.getLocalAddress();
				log.info(">>>>>>>>>>内网IP地址为:"+Contants.LAN_IP);
				s.close();
				return;
			} catch (IOException e) {
				log.info(">>>>>>>>>>设置本机内网IP地址失败!>>>>>>>>>>>>");
				e.printStackTrace();
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				continue;
			}
		}
	}
	public static void main(String []args){
		NetUtils.setCIP();
		NetUtils.setLanIp();
	}
	
}
